﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using log4net;
using log4net.Repository.Hierarchy;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Newtonsoft.Json.Converters;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class CouponController : BaseController
    {
        #region 列表页
        public ActionResult List()
        {
            return View();
        }
        
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult Listing(int draw, int start, int length)
        {
            try
            {
                int order;
                int.TryParse(Request["order[0][column]"], out order);
                string direction = Request["order[0][dir]"];
                var orderByColumns = new[] { "CouponName", "TotalQuantity", "SendQuantity", "CardValue", "StartTime", "EndTime", "Id" };
                string search = Request["search[value]"];

                TableDataViewDto<ViewCouponDto> theList = CouponBLL.Instance.GetPagingList(draw, (start / length) + 1, length, SqlSafe(search),
                    orderByColumns[order] + " " + direction);
                JsonResult jsonResult = Json(theList);
                jsonResult.MaxJsonLength = int.MaxValue;

                return jsonResult;
            }
            catch (Exception ex)
            {
                Logger.Error("Coupon Listing Catch Error: " + ex.Message);
                return Json(false);
            }
        }
        #endregion

        public ActionResult Create()
        {
            InitiSet();
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, Coupon model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            var couponCategory = CouponCategoryBLL.Instance.GetModel(model.CouponCategoryId);
            if (couponCategory != null)
            {
                model.CouponCategoryId = couponCategory.Id;
            }
            model.Subtitle = model.CouponName;
            model.IsPlatform = true;
            model.IsLimitCommodity = false;
            model.IsLimitBrand = false;
            model.AddTime = DateTime.Now;
            model.IsLimitCommodity = true;
            model.IsLimitCommodity = !string.IsNullOrEmpty(model.CommodityLibArr) ? true : false;
            model.IsLimitBrand = !string.IsNullOrEmpty(model.CommodityCategoryArr) ? true : false;
            int result = CouponBLL.Instance.Add(model);
            if (result > 0)
                if (!string.IsNullOrEmpty(model.CommodityLibArr))
                {
                    int[] ids = model.CommodityLibArr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
                    foreach (var item in ids)
                    {
                        CouponCommodityLibBLL.Instance.Add(new CouponCommodityLib() { CommodityLibId = item, CouponId = result, IsDelete = false });
                    }
                }
            if (!string.IsNullOrEmpty(model.CommodityCategoryArr))
            {
                int[] ids = model.CommodityCategoryArr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
                foreach (var item in ids)
                {
                    CouponCommodityCategoryBLL.Instance.Add(new CouponCommodityCategory() { CommodityCategoryId = item, CouponId = result, IsDelete = false });
                }
            }
            return RedirectToAction("List", "Coupon");
            Logger.Error("Coupon Create  Error: 优惠劵:" + model.CouponName + "添加失败");
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        public ActionResult Update(int id)
        {
            if (id <= 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            try
            {
                InitiSet();
                var model = CouponBLL.Instance.GetModel(id);

                var couponCommodityLibList = CouponCommodityLibBLL.Instance.GetModelList(string.Format("CouponId={0}", id));
                couponCommodityLibList.ForEach(c =>
             {
                 model.CommodityLibArr += c.CommodityLibId + ",";
                 var coupon = CommodityLibBLL.Instance.GetModel(c.CommodityLibId);
                 model.CommodityLibText += coupon != null ? coupon.CommodityName + "," : "";
             });
                if (!string.IsNullOrEmpty(model.CommodityLibText))
                {
                    model.CommodityLibText = "(" + model.CommodityLibText.Trim(',') + ")";
                }
                var couponCommodityCategory = CouponCommodityCategoryBLL.Instance.GetModelList(string.Format("CouponId={0}", id));
                couponCommodityCategory.ForEach(c =>
                {
                    model.CommodityCategoryArr += c.CommodityCategoryId + ",";
                    var coupon = CommodityCategoryBLL.Instance.GetModel(c.CommodityCategoryId);
                    model.CommodityCategoryText += coupon != null ? coupon.CategoryName + "," : "";
                });
                if (!string.IsNullOrEmpty(model.CommodityCategoryText))
                {
                    model.CommodityCategoryText = "(" + model.CommodityCategoryText.Trim(',') + ")";
                }
                return View(model);
            }
            catch (Exception ex)
            {
                Logger.Error("Coupon Update catch Error: 优惠劵:" + ex.Message);
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }


        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, Coupon model)
        {
            var coupon = CouponBLL.Instance.GetModel(model.Id);
            if (coupon == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            coupon.Subtitle = model.CouponName;
            coupon.CouponName = model.CouponName;
            coupon.TotalQuantity = model.TotalQuantity;
            coupon.DiscountValue = model.DiscountValue;
            coupon.CardValue = model.CardValue;
            coupon.StartTime = model.StartTime;
            coupon.EndTime = model.EndTime;
            coupon.Description = model.Description;
            coupon.Instruction = model.Instruction;
            coupon.Disclaimer = model.Disclaimer;
            coupon.IsMultiUse = model.IsMultiUse;
            coupon.IsLimitCommodity = !string.IsNullOrEmpty(model.CommodityLibArr) ? true : false;
            coupon.IsLimitBrand = !string.IsNullOrEmpty(model.CommodityCategoryArr) ? true : false;
            var result = CouponBLL.Instance.Update(coupon);
            if (result)
                if (!string.IsNullOrEmpty(model.CommodityLibArr))
                {
                    CouponCommodityLibBLL.Instance.DeleteByCommodityLibId(model.Id);
                    int[] ids =
                        model.CommodityLibArr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(int.Parse)
                            .ToArray();
                    foreach (var item in ids)
                    {
                        CouponCommodityLibBLL.Instance.Add(new CouponCommodityLib()
                        {
                            CommodityLibId = item,
                            CouponId = model.Id,
                            IsDelete = false
                        });
                    }
                }
                else
                {
                    CouponCommodityLibBLL.Instance.DeleteByCommodityLibId(model.Id);
                }
            if (!string.IsNullOrEmpty(model.CommodityCategoryArr))
            {
                CouponCommodityCategoryBLL.Instance.DeleteByCouponId(model.Id);
                int[] ids =
                    model.CommodityCategoryArr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(int.Parse)
                        .ToArray();
                foreach (var item in ids)
                {
                    CouponCommodityCategoryBLL.Instance.Add(new CouponCommodityCategory()
                    {
                        CommodityCategoryId = item,
                        CouponId = model.Id,
                        IsDelete = false
                    });
                }
            }
            else
            {
                CouponCommodityCategoryBLL.Instance.DeleteByCouponId(model.Id);
            }
            return RedirectToAction("List", "Coupon");

            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        [HttpPost]
        public JsonResult Delete()
        {
            var ids = Request["doIds"];
            var result = CouponBLL.Instance.DeleteList(ids);
            return Json(result);

        }

        /// <summary>
        /// 所有数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetCount()
        {
            var data = CouponBLL.Instance.GetTotalCount();
            return Json(data);
        }

        /// <summary>
        /// 搜索品类
        /// </summary>
        /// <param name="keyWords"></param>
        /// <returns></returns>
        public JsonResult GetCommodityCategoryList(string keyWords)
        {
            var result = new Result<List<CommodityCategory>>();
            var list = CommodityCategoryBLL.Instance.GetModelList(string.Format("CategoryName like '%{0}%'", keyWords));
            if (list != null)
            {
                list.ForEach(s
                    =>
                {
                    if (string.IsNullOrEmpty(s.Description))
                    {
                        s.Description = "";
                    }
                });

                result = new Result<List<CommodityCategory>>
                {
                    Status = true,
                    Message = "Success",
                    Data = list
                };
            }
            else
            {
                result.Message = "品类不存在！";
            }
            return Json(result);
        }

        /// <summary>
        /// 搜索商品
        /// </summary>
        /// <param name="keyWords"></param>
        /// <returns></returns>
        public JsonResult GetCommodityLibList(string keyWords)
        {
            var result = new Result<List<CommodityLib>>();
            var commodityLibList = CommodityLibBLL.Instance.GetModelList(string.Format("CommodityName like '%{0}%'", keyWords));
            if (commodityLibList != null)
            {
                commodityLibList.ForEach(c =>
                {
                    if (c.BrandId > 0)
                    {
                        var commodityBrand = CommodityBrandBLL.Instance.GetModel(c.BrandId);
                        c.BrandName = commodityBrand != null ? commodityBrand.BrandName : string.Empty;
                    }
                });

                result = new Result<List<CommodityLib>>
                {
                    Status = true,
                    Message = "Success",
                    Data = commodityLibList
                };
            }
            else
            {
                result.Message = "商品不存在！";
            }
            return Json(result);
        }
        private void InitiSet()
        {


            List<SelectListItem> lsCategories =
              CouponCategoryBLL.Instance.GetModelList().Select(model => new SelectListItem
                {
                    Value = model.Id.ToString(),
                    Text = model.CategoryName
                }).ToList();
            ViewBag.CouponCategory = lsCategories;


        }

    }
}
